#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import sys
import time
import re
import tweepy
from polgr.main import model_handling as mh 
import datetime

def Parse(text,tl):
    sentiments = {":)":0,
                  ":|":0,
                  ":(":0,}

    t=text.split(" ")
    l=list(set(t) & set(tl))
    for s in sentiments.keys():
        sentiments[s] = text.count(s)
    ss = []
    for s,n in sentiments.items():
        if n > 0:
            ss.append(s)
    if len(ss) == 1:
	if ss[0] == ":)":
           return l,1
	elif ss[0] == ":|":
           return l,0
 	else:
           return l,-1
    else:
        return [],None

class StreamWatcherListener(tweepy.StreamListener):
    orgs = mh.GetOrganisationKeywords()
    persons = mh.GetPersonKeywords()
    maxt = []
    def on_status(self, status):
        t1=time.time()
        try:
            sender = status.author.screen_name
            par,sent = Parse(status.text,self.orgs)
            print par,sent
            for p in par:
                mh.AddOrganisationVote(sender,p,sent)
            pol,sent = Parse(status.text,self.persons)
            for p in pol:
                mh.AddPersonVote(sender,p,sent)
            t2=time.time()
            self.maxt.append(t2-t1)
            print max(self.maxt),float(sum(self.maxt))/float(len(self.maxt))
        except Exception,e:
            print "Error %s" %e
    def on_error(self, status_code):
        print 'An error has occured! Status code = %s' % status_code
        return True  # keep stream alive
 
    def on_timeout(self):
        print 'Snoozing Zzzzzz'
 
def main(username,password):
    # Prompt for login credentials and setup stream object
    stream = tweepy.Stream(username, password, StreamWatcherListener(), timeout=None)
 
    track_list = ['@pasok']
 
    stream.filter([], track_list)

def test():
    orgs = mh.GetOrganisationKeywords()
    persons = mh.GetPersonKeywords()
    ts = [
	   ['s2','dedeye @pasok dedede @kke :)'],
	   ['s1','dedeye @pasok dedede @kke :('],
	   ['s3','dedeye @pasok dedede @syriza :('],
	   ['s4','dedeye @pasok dedede @kke :('],
	]
    for s in ts:
        sender = s[0]
        par,sent = Parse(s[1],orgs)
        print par,sent
        for p in par:
           mh.AddOrganisationVote(sender,p,sent)
        pol,sent = Parse(s[1],persons)
        for p in pol:
           mh.AddPersonVote(sender,p,sent)
	 
if __name__ == '__main__':
    if len(sys.argv) < 2:
        print "Usage %s <user> <password>" %sys.argv[0]
        sys.exit(10)
    user = sys.argv[1]
    passwd = sys.argv[2]
    try:
#        main(user,passwd)
	test() 
    except KeyboardInterrupt:
        print '\nGoodbye!'
 
